<template>
  <div class="editor-container">
    <!-- 左侧组件库 -->
    <div class="component-library">
      <h3>文本组件库</h3>
      <div class="component-list">
        <!-- 文本组件项 - 可拖拽 -->
        <div 
          class="component-item" 
          v-for="component in textComponents" 
          :key="component.id"
          draggable="true"
          @dragstart="onDragStart($event, component)"
          :title="component.name"
        >
          <div class="component-icon">{{ component.icon }}</div>
          <div class="component-name">{{ component.name }}</div>
        </div>
      </div>
    </div>

    <!-- 中间预览区域 -->
    <div class="preview-area" @dragover="onDragOver" @drop="onDrop">
      <h3>预览区域</h3>
      <!-- 已添加的文本组件 -->
      <div v-for="(block, index) in textBlocks" :key="block.id" class="preview-content">
        <vue-draggable-resizable
          :x="block.position.x"
          :y="block.position.y"
          :w="block.size.width"
          :h="block.size.height"
          :min-width="100"
          :min-height="40"
          :is-active="activeBlockId === block.id"
          @activated="setActiveBlock(block.id)"
          @deactivated="setActiveBlock(null)"
          @dragstop="onBlockDragStop(index, $event.x, $event.y)"
          @resizestop="onBlockResizeStop(index, $event.width, $event.height)"
          class="draggable-text"
        >
          <!-- 文本内容区域 -->
          <div class="text-container">
            <div 
              class="editable-content"
              :contenteditable="block.isEditing"
              @input="updateBlockContent(index, $event)"
              @dblclick="toggleBlockEditing(index)"
              @blur="stopBlockEditing(index)"
            >
              {{ block.content }}
            </div>
            <!-- 添加编辑按钮，仅在非编辑状态显示 -->
            <button 
              class="edit-button" 
              v-if="!block.isEditing && activeBlockId === block.id"
              @click.stop="startBlockEditing(index)"
              title="点击编辑"
            >
              编辑
            </button>
          </div>
        </vue-draggable-resizable>
        <!-- 删除按钮 -->
        <button 
          class="delete-button" 
          v-if="activeBlockId === block.id"
          @click.stop="removeBlock(index)"
          title="删除组件"
        >
          ×
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from 'vue';
import VueDraggableResizable from 'vue-draggable-resizable';
import 'vue-draggable-resizable/dist/VueDraggableResizable.css';

Vue.component('vue-draggable-resizable', VueDraggableResizable);

export default {
  // name: "moduleIndex",
  data() {
    return {
      // 左侧组件库数据
      textComponents: [
        {
          id: 'text1',
          name: '普通文本',
          icon: 'T',
          defaultContent: '双击编辑文本',
          defaultSize: { width: 200, height: 80 }
        },
        {
          id: 'text2',
          name: '标题文本',
          icon: 'H',
          defaultContent: '这是标题',
          defaultSize: { width: 300, height: 60 }
        },
        {
          id: 'text3',
          name: '段落文本',
          icon: 'P',
          defaultContent: '这是一段示例文本，您可以双击编辑它。',
          defaultSize: { width: 400, height: 100 }
        }
      ],
      // 中间预览区域的文本块数组
      textBlocks: [],
      // 当前激活的文本块ID
      activeBlockId: null,
      // 拖拽相关
      draggedComponent: null
    };
  },
  methods: {
    // 拖拽开始 - 左侧组件到预览区
    onDragStart(event, component) {
      this.draggedComponent = component;
      event.dataTransfer.effectAllowed = 'copy';
    },

    // 拖拽经过预览区
    onDragOver(event) {
      event.preventDefault();
      event.dataTransfer.dropEffect = 'copy';
    },

    // 拖拽释放到预览区
    onDrop(event) {
      event.preventDefault();
      
      if (this.draggedComponent) {
        // 获取相对于预览区的坐标
        const previewArea = event.currentTarget;
        const rect = previewArea.getBoundingClientRect();
        const x = event.clientX - rect.left - 15; // 调整位置使其居中
        const y = event.clientY - rect.top - 15;

        // 添加新的文本块到预览区域
        this.textBlocks.push({
          id: `${this.draggedComponent.id}_${Date.now()}`,
          content: this.draggedComponent.defaultContent,
          position: { x: Math.max(0, x), y: Math.max(0, y) },
          size: { ...this.draggedComponent.defaultSize },
          isEditing: false
        });

        // 清除拖拽状态
        this.draggedComponent = null;
      }
    },

    // 设置当前激活的文本块
    setActiveBlock(blockId) {
      this.activeBlockId = blockId;
    },

    // 文本块拖拽结束
    onBlockDragStop(index, x, y) {
      // this.textBlocks[index].position.x = x;
      // this.textBlocks[index].position.y = y;
    },

    // 文本块调整大小结束
    onBlockResizeStop(index, width, height) {
      // this.textBlocks[index].size.width = width;
      // this.textBlocks[index].size.height = height;
    },

    // 更新文本块内容
    updateBlockContent(index, event) {
      // 保存当前内容
      const newContent = event.target.innerText;
      
      // 更新数据
      this.textBlocks[index].content = newContent;
      
      // 强制DOM更新后设置光标位置
      // this.$nextTick(() => {
      //   this.setCursorToEnd(index);
      // });
    },
    
    // 将光标设置到文本末尾
    setCursorToEnd(index) {
      // 获取所有可编辑元素
      const elements = document.querySelectorAll('.editable-content');
      const editable = elements[index];
      
      if (editable) {
        // 保存焦点状态
        const hasFocus = document.activeElement === editable;
        
        // 创建范围对象并设置光标位置
        const range = document.createRange();
        const selection = window.getSelection();
        
        // 确保元素内容已更新
        if (editable.firstChild) {
          // 选择最后一个子节点的末尾
          range.selectNodeContents(editable);
          range.collapse(false); // false 表示光标放在内容的最后面
          
          // 添加范围到选择对象
          selection.removeAllRanges();
          selection.addRange(range);
          
          // 如果元素之前有焦点，则重新获取焦点
          if (!hasFocus) {
            editable.focus();
          }
        }
      }
    },

    // 切换文本块编辑状态
    toggleBlockEditing(index) {
      this.textBlocks[index].isEditing = !this.textBlocks[index].isEditing;
      if (this.textBlocks[index].isEditing) {
        this.$nextTick(() => {
          this.setCursorToEnd(index);
        });
      }
    },

    // 开始编辑文本块
    startBlockEditing(index) {
      this.textBlocks[index].isEditing = true;
      this.$nextTick(() => {
        this.setCursorToEnd(index);
      });
    },

    // 停止编辑文本块
    stopBlockEditing(index) {
      this.textBlocks[index].isEditing = false;
    },

    // 删除文本块
    removeBlock(index) {
      this.textBlocks.splice(index, 1);
      if (this.activeBlockId) {
        this.activeBlockId = null;
      }
    },

    // 将光标设置到文本末尾
    setCursorToEnd(index) {
      const elements = document.querySelectorAll('.editable-content');
      const editable = elements[index];
      if (editable) {
        editable.focus();
        const range = document.createRange();
        const selection = window.getSelection();
        range.selectNodeContents(editable);
        range.collapse(false); // false 表示光标放在内容的最后面
        selection.removeAllRanges();
        selection.addRange(range);
      }
    }
  }
};
</script>

<style scoped>
.editor-container {
  display: flex;
  width: 100%;
  height: 100vh;
  background-color: #f5f7fa;
}

/* 左侧组件库样式 */
.component-library {
  width: 200px;
  background-color: #fff;
  border-right: 1px solid #e6e6e6;
  padding: 20px;
  overflow-y: auto;
}

.component-library h3 {
  margin: 0 0 15px 0;
  font-size: 16px;
  color: #333;
  border-bottom: 1px solid #e6e6e6;
  padding-bottom: 10px;
}

.component-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.component-item {
  display: flex;
  align-items: center;
  padding: 10px;
  background-color: #f9f9f9;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  cursor: move;
  transition: all 0.3s;
}

.component-item:hover {
  background-color: #e6f7ff;
  /* border-color: #409eff; */
}

.component-icon {
  width: 30px;
  height: 30px;
  background-color: #409eff;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10px;
  font-weight: bold;
}

.component-name {
  font-size: 14px;
  color: #666;
}

/* 中间预览区域样式 */
.preview-area {
  flex: 1;
  position: relative;
  padding: 20px;
  overflow: auto;
}

.preview-area h3 {
  margin: 0 0 15px 0;
  font-size: 16px;
  color: #333;
}

.preview-content {
  position: relative;
}

/* 拖拽文本组件样式 */
.draggable-text {
  background-color: #fff;
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

.text-container {
  width: 100%;
  height: 100%;
  /* padding: 10px; */
  box-sizing: border-box;
  position: relative;
}

.editable-content {
  width: 100%;
  height: 100%;
  outline: none;
  overflow: auto;
}

/* 编辑按钮样式 */
.edit-button {
  position: absolute;
  top: 5px;
  right: 5px;
  padding: 4px 10px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  z-index: 10;
}

.edit-button:hover {
  background-color: #66b1ff;
}

/* 删除按钮样式 */
.delete-button {
  position: absolute;
  top: -15px;
  right: -15px;
  width: 30px;
  height: 30px;
  background-color: #ff4949;
  color: white;
  border: none;
  border-radius: 50%;
  cursor: pointer;
  font-size: 20px;
  line-height: 30px;
  text-align: center;
  z-index: 20;
}

.delete-button:hover {
  background-color: #ff7875;
}

/* 编辑状态样式 */
.editable-content[contenteditable="true"] {
  border: 1px solid #409eff;
  /* border-radius: 4px; */
  /* padding: 5px; */
}
</style>
